package org.dromara.iot.controller;


import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.iot.domain.AppUpdateInfoVo;
import org.dromara.system.domain.vo.SysDictDataVo;
import org.dromara.system.service.ISysDictTypeService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.List;
import java.util.Optional;

@SaIgnore
@RequiredArgsConstructor
@RestController
@RequestMapping(value = "/updateApp")
@Slf4j
public class UpdateAppController {
    private final ISysDictTypeService sysDictTypeService;
    private static final String APP_UPDATE_INFO = "app_update_info";
    private static final String LASTED = "latest_version";
    private static final String ANDROID = "android";
    private static final String IOS = "ios";

    @GetMapping(value = "/getInfo")
    public R<AppUpdateInfoVo> getUpdateInto(String versionCode, String platform) {
        log.info("UpdateAppController versionCode = {},plantForm ={}", versionCode, platform);
        List<SysDictDataVo> sysDictDataVos = sysDictTypeService.selectDictDataByType(APP_UPDATE_INFO);
        if (CollUtil.isNotEmpty(sysDictDataVos)) {
            Optional<SysDictDataVo> first = sysDictDataVos.stream().min(Comparator.comparing(SysDictDataVo::getDictSort));
            if (first.isPresent()) {
                SysDictDataVo sysDictDataVo = first.get();
                if (StringUtils.isBlank(sysDictDataVo.getRemark())) {
                    return R.ok();
                }
                AppUpdateInfoVo bean = JSONUtil.toBean(sysDictDataVo.getRemark(), AppUpdateInfoVo.class);
                if (bean.getVersion().equals(versionCode)) {
                    return R.ok();
                }
                return R.ok(bean);
            }
        }
        return R.ok();
    }

}
